/**
 * @author sam
 * @date 2018-07-24
 * @type {string[]}
 * @Todo 基于metronic v5.0 实现的自定义tab页，主要是加入了关闭按钮及鼠标右键菜单；其中右键菜单基于jquery 脚本没有依赖metronic,可以单独剥离
 * 此TAB已经被编辑过,结合 最新住建首页 opus-front使用
 */
var tabs = function () {};

//tab菜单编号数组
var openedCode = new Array('model');

//右键菜单对象
var kyoPopupMenu = {};

//iframe区域点击事件
var IframeOnClick = {
  resolution: 200,
  iframes: [],
  interval: null,
  Iframe: function () {
    this.element = arguments[0];
    this.cb = arguments[1];
    this.hasTracked = false;
  },
  track: function (element, cb) {
    this.iframes.push(new this.Iframe(element, cb));
    if (!this.interval) {
      var _this = this;
      this.interval = setInterval(function () {
        _this.checkClick();
      }, this.resolution);
    }
  },
  checkClick: function () {
    if (document.activeElement) {
      var activeElement = document.activeElement;
      for (var i in this.iframes) {
        if (activeElement === this.iframes[i].element) { // user is in this Iframe
          if (this.iframes[i].hasTracked == false) {
            this.iframes[i].cb.apply(window, []);
            this.iframes[i].hasTracked = true;
          }
        } else {
          this.iframes[i].hasTracked = false;
        }
      }
    }
  }
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};
Array.prototype.remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

//初始化tab
tabs.custom = {
  initTab: function () {
    //点击菜单打开tab页
    $('.m-menu__link').on('click', function () {
      openTab($(this), '.m-menu__link-text');
    });
    //初始化右键菜单
    kyoPopupMenu = (function () {
      return {
        sys: function (code) {
          $('.popup_menu').remove();
          popupMenuApp = $('<div class="popup_menu app-menu"><ul>' +
              '<li><a menu="menu1"><i class="fa fa-times"></i> 关闭其他标签页</a></li>' +
              '<li><a menu="menu2"><i class="fa fa-times"></i> 关闭左边标签页</a></li>' +
              '<li><a menu="menu3"><i class="fa fa-times"></i> 关闭右边标签页</a></li>' +
              '</ul></div>')
            .find('a').attr('href', 'javascript:;')
            .end().appendTo('body');
          //绑定事件
          $('.app-menu a[menu="menu1"]').on('click', function () {
            tabs.custom.closeOtherTab(code);
            $('.popup_menu').hide();
          });
          $('.app-menu a[menu="menu2"]').on('click', function () {
            tabs.custom.closeLeftTab(code);
            $('.popup_menu').hide();
          });
          $('.app-menu a[menu="menu3"]').on('click', function () {
            tabs.custom.closeRightTab(code);
            $('.popup_menu').hide();
          });
          return popupMenuApp;
        }
      }
    })();
    //取消右键菜单
    $('html').on('contextmenu', function () {
      return false;
    }).click(function (event) {
      $('.popup_menu').hide();
    });
  },
  //切换tab页
  checkTab: function (code) {

    $("#item_" + code).trigger('click');

    //桌面点击右击
    $("#item_" + code).on('contextmenu', function (e) {
      var popupmenu = kyoPopupMenu.sys(code);
      l = ($(document).width() - e.clientX) < popupmenu.width() ? (e.clientX - popupmenu.width()) : e.clientX;
      t = ($(document).height() - e.clientY) < popupmenu.height() ? (e.clientY - popupmenu.height()) : e.clientY;
      popupmenu.css({
        left: l,
        top: t
      }).show();
      return false;
    });
    //取消右键菜单
    IframeOnClick.track(document.getElementById("iframe_" + code), function () {
      $('.popup_menu').hide();
    });
    AleftLiActive(code);
  },
  //关闭tab页
  closeTab: function (code) {
    var tabItem = $('#item_' + code).parent();
    var tabPanel = $('#m_tabs_' + code);
    tabPanel.remove();
    tabItem.remove();
    var index = openedCode.indexOf(code);
    openedCode.remove(code);
    tabs.custom.checkTab(openedCode[index - 1]);
    //leftLiActive(openedCode[index-1]);
  },
  //关闭其他所有tab
  closeOtherTab: function (code) {
    var newOpenedCode = new Array('model');
    newOpenedCode.push(code);

    tabs.custom.checkTab(code);

    var index = openedCode.indexOf(code);
    if (index > 0) {
      for (var i = 0; i < openedCode.length; i++) {
        var currCode = openedCode[i];
        if (currCode != 'model' && currCode != code) {
          var tabItem = $('#item_' + currCode).parent();
          var tabPanel = $('#m_tabs_' + currCode);
          tabPanel.remove();
          tabItem.remove();
        }
      }
      openedCode = newOpenedCode;
    }
  },
  //关闭左边tab页
  closeLeftTab: function (code) {
    var newOpenedCode = new Array('model');

    tabs.custom.checkTab(code);

    var index = openedCode.indexOf(code);
    for (var i = index; i < openedCode.length; i++) {
      newOpenedCode.push(openedCode[i]);
    }

    for (var i = 0; i < openedCode.length; i++) {
      var currCode = openedCode[i];
      if ($.inArray(currCode, newOpenedCode) == -1) {
        var tabItem = $('#item_' + currCode).parent();
        var tabPanel = $('#m_tabs_' + currCode);
        tabPanel.remove();
        tabItem.remove();
      }
    }
    openedCode = newOpenedCode;
  },
  //关闭右边tab页
  closeRightTab: function (code) {
    var newOpenedCode = new Array();

    var index = openedCode.indexOf(code);
    for (var i = 0; i <= index; i++) {
      newOpenedCode.push(openedCode[i]);
    }

    tabs.custom.checkTab(openedCode[index]);

    for (var i = 0; i < openedCode.length; i++) {
      var currCode = openedCode[i];
      if ($.inArray(currCode, newOpenedCode) == -1) {
        var tabItem = $('#item_' + currCode).parent();
        var tabPanel = $('#m_tabs_' + currCode);
        tabPanel.remove();
        tabItem.remove();
      }
    }
    openedCode = newOpenedCode;
  }
}

var leftLiActive = function (code) {
  //添加选中效果
  $.each($('#m_ver_menu ul li'), function (index, item) {
    //如果code相等
    if ($(item).find("a").data('code') == code) {
      $(item).addClass('m-menu__item--active');
    } else {
      $(item).removeClass('m-menu__item--active');
    }
  });
}

var AleftLiActive = function (code) {
  var url = $('#item_'+code).attr('data-href');
  $('#iframe'+code).attr('src', url);
  showTabs();
}

var ACloseTab = function (code) {
  // alert('onClose-tab');
  tabs.custom.closeTab(code);
}
var ACloseHiddenTab = function (code) {
  closeHiddenTab(code);
}

var closeHiddenTab = function (code) {
  alert(code);
  var tabItem = $('#hideitem_' + code);
  var tabPanel = $('#m_tabs_' + code);
  tabPanel.remove();
  tabItem.empty();
  var index = openedCode.indexOf(code);
  openedCode.remove(code);
  tabs.custom.checkTab(openedCode[index - 1]);
  //leftLiActive(openedCode[index-1]);
}

function openTab(ele, textClass) {
  var code = $(ele).data('code');
  if (!code) {
    return;
  }
  var url = $(ele).data('url');
  if (url) {
    var title = $(ele).children('' + textClass).html();
    //是否存在已打开的 code相同tab
    var index = $.inArray(code, openedCode);
    var maxCount = fetchCurrentWidth();
    if (index < 0 && openedCode.length >= maxCount) tabs.custom.closeTab(openedCode[1]); //关闭最前面一个
    if (index < 0) {
      var tabItem = '<li class="nav-item m-tabs__item show">\n' +
        '<a class="nav-link m-tabs__link" id="item_' + code + '" data-toggle="tab" data-href="' +
        url + '" href="#m_tabs_' + code + '"  onclick="AleftLiActive(\'' + code + '\'); " role="button" aria-haspopup="true" aria-expanded="false">' +
        title + '<i class="fa fa-times" onclick="ACloseTab(\'' + code + '\')"></i></a>\n' +
        '</li>';
      var tabPanel = '<div class="tab-pane" id="m_tabs_'+code+'" role="tabpanel">\n' +
        '<iframe src="'+url+'"  frameborder=\'0\' name="_blank" id="iframe_'+code+'" ></iframe>\n' +
        '</div>';
      $('#tab_content').append(tabPanel);
      $('#tab_list').append(tabItem);
      openedCode.push(code);
    }
  } else { //有二级菜单
    $.each($('#m_header_menu ul li'), function (index, item) {
      //如果code相等
      if ($(item).find("a").data('code') == code) {
        $(item).addClass('m-menu__item--active');
      } else {
        $(item).removeClass('m-menu__item--active');
      }
    }); //选中一级菜单
    initLeftMenu(ele);
  }
  tabs.custom.checkTab(code);
}
/* topbar的li的html内容渲染*/
function initLeftMenu(elem) {
  var parent = $(elem).parent();
  /*获取li数组*/
  var menuInfoArr = parent.find("ul li");
  /*获取左竖栏容器ID*/
  var containerId = 'm_ver_menu';
  var container = $('#' + containerId + " ul");

  //容器清空
  container.empty();
  //容器 添加li
  var sumEntity = {
    'menuCount': menuInfoArr.length
  }
  addSum(containerId, sumEntity);
  menuInfoArr.each(function () {
    addEntity(containerId, $(this));
  })
  //打开页面
  var elem = container.find("li a");
  //绑定 leftbar的li点击事件
  initLeftArrayLiA(elem);
  //检查当前opendCode是否匹配 新打开的左竖栏
  var currentOpenCode = $('#tab_list li a.active.show').attr('id') + '';
  currentOpenCode = currentOpenCode.substr(5); //从 'item_'之后截取
  //根据tab当前code选中左竖栏菜单
  leftLiActive(currentOpenCode);
  //如果tab没有打开的元素,则默认打开第一个
  /*if(openedCode.length==1){
      $('#'+containerId+" ul li a")[0].click();
  }*/
}

function addSum(containerId, sumEntity) {
  var container = $('#' + containerId);
  var html = "";

  $(html).appendTo(container);
}

function addEntity(containerId, entity) {
  //debugger;
  var taskNum = '';
  var DoneTask = '';
  var container = $('#' + containerId + " ul");
  var menuName = $(entity).attr('id');
  var menuCode = $(entity).data('code');
  //查询代办事项数量  动态变化  如果变了就有问题  //menuCode=='opu-rs-menu-00000000077' || menuCode=='opu-rs-menu-00000000082'
  if (/(待办)+/.test(menuName)) {
    taskNum = loadTaskToDo('720f70a6-67b5-4558-b6cf-4f9c4d966d3b');
    if (typeof (taskNum) == "undefined") {
      taskNum = 0;
    }
  }
  //查询已办事项数量  动态变化  如果变了就有问题  menuCode=='opu-rs-menu-00000000078' || menuCode=='opu-rs-menu-00000000083'
  if (/(已办)+/.test(menuName)) {
    taskNum = loadTaskToDo('ce8ca4c1-1907-4140-99ab-affb214d2384');
    if (typeof (taskNum) == "undefined") {
      taskNum = 0;
    }
  }

  if (/(待预审)+/.test(menuName)) {
    taskNum = loadTaskToDo('1b4b0d28-38b6-4516-b79b-b6a5e9d5f0f3');
    if (typeof (taskNum) == "undefined") {
      taskNum = 0;
    }
  }

  if (/(已预审)+/.test(menuName)) {
    taskNum = loadTaskToDo('20895803-25fb-436a-9fbd-1ac08f0d9f33');
    if (typeof (taskNum) == "undefined") {
      taskNum = 0;
    }
  }

  var menuIcoCss = $(entity).data('ico-css');
  var url = $(entity).attr('url');
  // url='${pageContext.request.contextPath}'+url;
  var html = "";
  html += '<li class="m-menu__item " > ';
  html += '  <a  href="#" class="m-menu__link m-menu__toggle"  data-code="' + menuCode + '"';
  html += '       data-url="' + url + '"';
  html += '    >';
  html += '<span class="m-menu__item-here"></span>\n' +
    '      <i class="m-menu__link-icon ' + menuIcoCss + '"></i>'
  html += '        <span class="m-menu__link-text">';
  html += '                ' + menuName + '';
  //menuCode是后台配置的，会有变化，如果变化后就无法显示了  menuCode=='opu-rs-menu-00000000077' || menuCode=='opu-rs-menu-00000000082'
  //menuName=='待办任务'|| menuCode=='opu-rs-menu-00000000078'  || menuCode=='opu-rs-menu-00000000083'
  if (/(待办)+/.test(menuName) || /(已办)+/.test(menuName) || /(待预审)+/.test(menuName) || /(已预审)+/.test(menuName)) {
    html += '        </span>' + '<span class="m-menu__link-title"> <span class="m-menu__link-wrap"> <span class="m-menu__link-badge"> <span class="m-badge m-badge--danger"> ' + taskNum + ' </span></span></span></span>';
  } else {
    html += '        </span>'
  };
  html += '    </a>    ';
  html += '</li>';
  $(html).appendTo(container);
}
//绑定leftBar上的li事件:点击菜单打开tab页
function initLeftArrayLiA(elem) {
  // $('.m-menu__link').
  $(elem).on('click', function () {
    openTab(this, '.m-menu__link-text');
  });
}
/*获取当前屏幕宽度*/
function fetchCurrentWidth() {
  var cssPaddingWidth=20;
  var tabFirstA=$('#item_model');
  var maxAllowTabCount=Math.round(($(window).width()-cssPaddingWidth)/tabFirstA.parent().width()*0.8);
  return maxAllowTabCount;
  //获取每(第一)个tab块宽度,算出最多支持多少个tab,超过以后附加到 hide下拉样式中
  //影响事件,LeftBar菜单点击、TopMenu含url菜单点击、UserShortCut菜单点击
}
// 展示tabs超长左右点击事件
function showTabs(){
  var ele = $('#tab_list .nav-item');
  for(var i=0;i<ele.length;i++){
    var top = $(ele[i]).offset().top;
    if(top>60){
      $('#tab_list').css('padding','0 40px')
      var top2 = $(ele[i]).offset().top;
      if(top2>60){
        var ele2 = $('#tab_list .nav-item.show');
        $(ele2[0]).removeClass('show').addClass('hide').hide();
      }
      $(ele[0]).removeClass('show').addClass('hide').hide();
      $('.prev-tabs, .next-tabs').show()
    }
  }
  if($(ele[ele.length-1]).hasClass('hide')){
    $('.next-tabs').removeClass('disabled')
  }else{
    $('.next-tabs').addClass('disabled')
  }
  if($(ele[0]).hasClass('hide')){
    $('.prev-tabs').removeClass('disabled')
  }else{
    $('.prev-tabs').addClass('disabled')
  }
}
$(document).on('click','.prev-tabs',function(){
  var eleShow = $('#tab_list .nav-item.show');
  var eleShowPrev = $(eleShow[0]).prev('.nav-item.hide');
  if(eleShowPrev.length>0){
    $(eleShow[eleShow.length-1]).removeClass('show').addClass('hide').hide();
    $(eleShowPrev).removeClass('hide').addClass('show').show();
  }
  showTabs();
})
$(document).on('click','.next-tabs',function(){
  var eleShow = $('#tab_list .nav-item.show');
  var eleNext = $(eleShow[eleShow.length-1]).next('.nav-item.hide');
  if(eleNext.length>0){
    $(eleShow[0]).removeClass('show').addClass('hide').hide();
    $(eleNext[0]).removeClass('hide').addClass('show').show();
  }
  showTabs();
})